import {getDetail} from "../../api/api.js"

Page({
  /**
   * 页面的初始数据
   */
  data: {
    'collection': false,
    x: 1000,
    y: 480
  },
  onTouchEnd: function () {
    var res = my.getSystemInfoSync();
    this.setData({
      x: res.windowWidth
    });
  },
  onPreviewImage: function (event) {
    var images = new Array();
    var process = this.data.data.process;

    for (var i in process) {
      images.push(process[i].pic);
    }

    my.previewImage({
      current: event.currentTarget.dataset.url,
      urls: images
    });
  },
  onPlay: function () {
    var appKey = "PLg7cLsPYPQpBehM6NQt1SoA";
    var appSecret = "nGpBqj0ROkhSTb9zNvzA9g61qGbKjItt";
    var that = this;
    var text = '';
    var per = my.getStorageSync({key: 'per'})['data'];
    var spd = my.getStorageSync({key: 'spd'})['data'];

    if (!spd) {
      spd = 5;
    } else {
      spd = spd - 1;
    }

    if (!per) {
      per = 0;
    }

    for (var i = 0; i < this.data.data.process.length; i++) {
      text += this.data.data.process[i].pcontent + '。';
      text = text.replace(/<[^>]+>/g, "");
      my.request({
        url: 'https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + appKey + '&client_secret=' + appSecret,
        method: 'get',
        dataType: 'json',
        success: function (res) {
          let audioCtx = wx.createAudioContext('myAudio');
          var url = 'http://tsn.baidu.com/text2audio?tex=' + text + '&lan=zh&cuid=zhaowenbin&ctp=1&spd=' + spd + '&per=' + per + '&tok=' + res.data.access_token;
          that.setData({
            src: url
          });
          audioCtx.play();
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var collection = my.getStorageSync({key: "collection"})['data'];

    if (!collection) {
      collection = new Array();
    }

    var exist = false;

    for (var i in collection) {
      if (options.id == collection[i].id) {
        this.setData({
          'data': collection[i],
          'collection': true
        });
        my.setNavigationBar({
          title: collection[i].name
        });
        exist = true;
      }
    }

    if (!exist) {
      my.showLoading({
        title: '加载中...'
      });
      var that = this;
      getDetail(options.id).then(res => {
        this.callBack(res)
      })
    } else {
      this.recordHistory();
      var auto = my.getStorageSync({key: 'auto'})['data'];

      if (auto) {
        this.onPlay();
      }
    } 

  },

  recordHistory() {
    var history = my.getStorageSync({key: "browse-history"})['data'];

    if (!history) {
      history = [];
    }

    let exist = false;

    for (var i in history) {
      if (this.data.data.id == history[i].id) {
        history.splice(i, 1);
        history.unshift(this.data.data);
        my.setStorageSync({key: 'browse-history', data: history});
        exist = true;
      }
    }

    if (!exist) {
      history.unshift(this.data.data);

      if (history.length > 100) {
        history.splice(history.length - 1, 1);
      }

      my.setStorageSync({key: 'browse-history', data: history});
    }
  },

  /**
   * 回调
   */
  callBack: function (ret) {
    var collection = my.getStorageSync({key: "collection"})['data'];
    ret.result.content = ret.result.content.replace(/<br \/>/g, "\n");
    this.setData({
      'data': ret.result
    });
    my.setNavigationBar({
      title: ret.result.name
    });
    my.hideLoading();

    if (!collection) {
      collection = new Array();
      my.setStorageSync({key: "collection", data: collection});
    } else {
      for (var i in collection) {
        if (this.data.data.id == collection[i].id) {
          this.setData({
            'collection': true
          });
        }
      }
    }

    var auto = my.getStorageSync({key: 'auto'})['data'];

    if (auto) {
      this.onPlay();
    }

    this.recordHistory();
  },
  onCollection: function () {
    var collection = my.getStorageSync({key: "collection"})['data'];
    if(!collection){
      collection = [];
    }
    if (this.data.collection) {
      for (var i in collection) {
        if (this.data.data.id == collection[i].id) {
          collection.splice(i, 1);
          my.setStorageSync({key: 'collection', data: collection});
        }
      }

      my.showToast({
        content: '取消收藏'
      });
      this.setData({
        'collection': false
      });
    } else {
      collection.unshift(this.data.data);
      my.setStorageSync({key: 'collection', data: collection});
      my.showToast({
        content: '收藏成功'
      });
      this.setData({
        'collection': true
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var res = my.getSystemInfoSync();
    this.setData({
      x: res.windowWidth
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  enterNcov: function(){
    my.navigateToMiniProgram({
      appId: '2021001132600368',
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.data.name,
      path: '/pages/index/list/detail/detail?id=' + this.data.data.id,
      success: function (res) {
        my.showToast({
          content: '分享成功'
        });
      },
      fail: function (res) {// 转发失败
      }
    };
  }
});